<template>
  <el-dialog
    v-model="dialogVisible"
    title="生成成绩证书"
    width="600px"
    :before-close="handleClose"
  >
    <div class="certificate-dialog">
      <!-- 证书预览 -->
      <div class="certificate-preview" ref="certificateRef">
        <div class="certificate-template">
          <div class="certificate-header">
            <h1 class="certificate-title">成绩证书</h1>
            <div class="certificate-subtitle">校园运动会</div>
          </div>

          <div class="certificate-body">
            <div class="certificate-content">
              <p class="certificate-text">
                兹证明 <strong>{{ selectedStudent?.name || 'XXX' }}</strong> 同学
                在 <strong>{{ selectedScore?.project?.name || 'XXX项目' }}</strong> 中
                表现优异，取得 <strong>{{ selectedScore?.score || 'XX' }}{{ selectedScore?.unit || '' }}</strong> 的成绩
              </p>

              <div class="certificate-details">
                <div class="detail-item">
                  <span class="label">学号：</span>
                  <span class="value">{{ selectedStudent?.studentNumber || 'XXXXXXXX' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">学院：</span>
                  <span class="value">{{ selectedStudent?.department || 'XXXXXXXX' }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">轮次：</span>
                  <span class="value">{{ getRoundText(selectedScore?.round) }}</span>
                </div>
                <div class="detail-item">
                  <span class="label">排名：</span>
                  <span class="value">
                    <span v-if="selectedScore?.rank <= 3" class="medal">{{ getMedalIcon(selectedScore?.rank) }}</span>
                    第{{ selectedScore?.rank || 'X' }}名
                  </span>
                </div>
                <div class="detail-item" v-if="selectedScore?.isRecord">
                  <span class="label">特殊成绩：</span>
                  <span class="value record-breaking">破纪录</span>
                </div>
              </div>
            </div>
          </div>

          <div class="certificate-footer">
            <div class="certificate-date">
              {{ formatDate(new Date()) }}
            </div>
            <div class="certificate-seal">
              <div class="seal-circle">
                <span class="seal-text">运动会组委会</span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 证书设置 -->
      <div class="certificate-settings">
        <el-form :model="certificateForm" label-width="100px">
          <el-form-item label="证书模板">
            <el-radio-group v-model="certificateForm.template">
              <el-radio-button label="classic">经典版</el-radio-button>
              <el-radio-button label="modern">现代版</el-radio-button>
              <el-radio-button label="elegant">优雅版</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="生成方式">
            <el-radio-group v-model="certificateForm.format">
              <el-radio-button label="pdf">PDF文件</el-radio-button>
              <el-radio-button label="image">图片文件</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="纸张尺寸">
            <el-select v-model="certificateForm.paperSize" style="width: 200px">
              <el-option label="A4 (210×297mm)" value="a4" />
              <el-option label="A3 (297×420mm)" value="a3" />
              <el-option label="Letter (216×279mm)" value="letter" />
            </el-select>
          </el-form-item>

          <el-form-item label="添加水印">
            <el-switch v-model="certificateForm.watermark" />
          </el-form-item>

          <el-form-item label="批量生成" v-if="scores.length > 1">
            <el-switch v-model="certificateForm.batch" />
            <span class="batch-hint">将为所有选中的成绩生成证书</span>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button @click="handlePreview" :loading="previewLoading">
          <el-icon><View /></el-icon> 预览
        </el-button>
        <el-button type="primary" @click="handleGenerate" :loading="generateLoading">
          <el-icon><Download /></el-icon> 生成证书
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { View, Download } from '@element-plus/icons-vue'
import { generateCertificate } from '@/api/score'
import html2canvas from 'html2canvas'

// 组件属性
const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  scores: {
    type: Array,
    default: () => []
  }
})

// 组件事件
const emit = defineEmits(['update:modelValue', 'close'])

// 对话框可见性
const dialogVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 证书预览引用
const certificateRef = ref(null)

// 加载状态
const previewLoading = ref(false)
const generateLoading = ref(false)

// 当前选中的成绩（用于预览）
const selectedScore = computed(() => props.scores[0] || {})
const selectedStudent = computed(() => selectedScore.value?.student || {})

// 证书表单
const certificateForm = reactive({
  template: 'classic',
  format: 'pdf',
  paperSize: 'a4',
  watermark: true,
  batch: false
})

// 获取轮次文本
const getRoundText = (round) => {
  const roundMap = {
    1: '第1轮',
    2: '第2轮',
    3: '第3轮',
    4: '决赛'
  }
  return roundMap[round] || '-'
}

// 获取奖牌图标
const getMedalIcon = (rank) => {
  if (rank === 1) return '🥇'
  if (rank === 2) return '🥈'
  if (rank === 3) return '🥉'
  return ''
}

// 格式化日期
const formatDate = (date) => {
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: 'long',
    day: 'numeric'
  })
}

// 处理关闭
const handleClose = () => {
  dialogVisible.value = false
  emit('close')
}

// 处理预览
const handlePreview = async () => {
  if (!certificateRef.value) return

  previewLoading.value = true
  try {
    // 使用html2canvas生成预览图
    const canvas = await html2canvas(certificateRef.value, {
      scale: 2,
      useCORS: true,
      backgroundColor: '#ffffff'
    })

    // 创建预览窗口
    const dataUrl = canvas.toDataURL('image/png')
    const previewWindow = window.open('', '_blank')
    previewWindow.document.write(`
      <html>
        <head>
          <title>证书预览</title>
          <style>
            body { margin: 0; padding: 20px; display: flex; justify-content: center; }
            img { max-width: 100%; height: auto; }
          </style>
        </head>
        <body>
          <img src="${dataUrl}" alt="证书预览" />
        </body>
      </html>
    `)

    ElMessage.success('预览生成成功')
  } catch (error) {
    console.error('预览生成失败:', error)
    ElMessage.error('预览生成失败')
  } finally {
    previewLoading.value = false
  }
}

// 处理生成证书
const handleGenerate = async () => {
  generateLoading.value = true
  try {
    const certificateData = {
      scores: certificateForm.batch ? props.scores : [selectedScore.value],
      template: certificateForm.template,
      format: certificateForm.format,
      paperSize: certificateForm.paperSize,
      watermark: certificateForm.watermark
    }

    const response = await generateCertificate(certificateData)

    if (response.code === 200) {
      // 处理下载
      if (certificateForm.format === 'pdf') {
        // 创建下载链接
        const url = window.URL.createObjectURL(new Blob([response.data], { type: 'application/pdf' }))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `成绩证书_${new Date().toLocaleDateString()}.pdf`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      } else {
        // 处理图片下载
        const url = window.URL.createObjectURL(new Blob([response.data], { type: 'image/png' }))
        const link = document.createElement('a')
        link.href = url
        link.setAttribute('download', `成绩证书_${new Date().toLocaleDateString()}.png`)
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
        window.URL.revokeObjectURL(url)
      }

      ElMessage.success('证书生成成功')
      handleClose()
    } else {
      ElMessage.error(response.message || '证书生成失败')
    }
  } catch (error) {
    console.error('证书生成失败:', error)
    ElMessage.error('证书生成失败')
  } finally {
    generateLoading.value = false
  }
}

// 监听模板变化
watch(() => certificateForm.template, () => {
  // 可以在这里根据模板更新预览样式
})
</script>

<style scoped>
.certificate-dialog {
  max-height: 80vh;
  overflow-y: auto;
}

.certificate-preview {
  margin-bottom: 24px;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 20px;
  background-color: #f9f9f9;
}

.certificate-template {
  background: linear-gradient(135deg, #f8f9fa, #ffffff);
  border: 2px solid #d4af37;
  border-radius: 8px;
  padding: 40px;
  text-align: center;
  position: relative;
  overflow: hidden;
}

.certificate-template::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image:
    radial-gradient(circle at 10% 20%, rgba(212, 175, 55, 0.1) 0%, transparent 50%),
    radial-gradient(circle at 90% 80%, rgba(212, 175, 55, 0.1) 0%, transparent 50%);
  pointer-events: none;
}

.certificate-header {
  margin-bottom: 30px;
}

.certificate-title {
  font-size: 36px;
  font-weight: bold;
  color: #2c3e50;
  margin: 0 0 8px 0;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.certificate-subtitle {
  font-size: 18px;
  color: #7f8c8d;
  font-style: italic;
}

.certificate-body {
  margin-bottom: 40px;
}

.certificate-content {
  max-width: 500px;
  margin: 0 auto;
}

.certificate-text {
  font-size: 18px;
  line-height: 1.8;
  color: #2c3e50;
  margin-bottom: 30px;
}

.certificate-details {
  text-align: left;
  background-color: rgba(255, 255, 255, 0.7);
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.detail-item {
  display: flex;
  margin-bottom: 12px;
  align-items: center;
}

.detail-item:last-child {
  margin-bottom: 0;
}

.label {
  font-weight: 500;
  color: #7f8c8d;
  min-width: 80px;
}

.value {
  color: #2c3e50;
  font-weight: 500;
}

.record-breaking {
  color: #e74c3c;
  font-weight: bold;
}

.medal {
  font-size: 18px;
  margin-right: 4px;
}

.certificate-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 40px;
}

.certificate-date {
  font-size: 16px;
  color: #7f8c8d;
  font-style: italic;
}

.certificate-seal {
  display: flex;
  align-items: center;
}

.seal-circle {
  width: 80px;
  height: 80px;
  border: 2px solid #d4af37;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
  background: radial-gradient(circle, rgba(212, 175, 55, 0.1), transparent);
}

.seal-text {
  font-size: 12px;
  color: #d4af37;
  font-weight: bold;
  text-align: center;
  line-height: 1.2;
}

.certificate-settings {
  background-color: #f8f9fa;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #e4e7ed;
}

.batch-hint {
  margin-left: 12px;
  font-size: 12px;
  color: #7f8c8d;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .certificate-template {
    padding: 20px;
  }

  .certificate-title {
    font-size: 28px;
  }

  .certificate-text {
    font-size: 16px;
  }

  .certificate-footer {
    flex-direction: column;
    gap: 16px;
  }
}
</style>